package com.gxa.day2022_07_29_21.homework.others.log;

import java.io.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Description:
 * @Author: zhuiyi
 * @CreatTime: 2022/7/30 22:02
 **/
public class LogObj {


    /**
     * 记录用户登陆信息。
     * @param info
     */
    public void writeLog(String info) throws IOException {
        List<String> stringList = new ArrayList<>();
        File dir = new File("e:/test/log");

        LocalDate now = LocalDate.now();
        String s = now.toString();
        s= dir.getAbsolutePath()+"/" + s + ".txt";
        File file = new File(s);//仅仅是建立文件在内存中的映射

        if (!dir.exists()){//如果目录不存在 创建目录
            dir.mkdir();
        }
        if(!file.exists()){//如果文件不存在，创建新文件
            file.createNewFile();
        }

        //读取
        FileReader fr = new FileReader(s);//节点流
        BufferedReader br = new BufferedReader(fr);//处理流
        String str = null;
        while ((str=br.readLine()) != null){
            stringList.add(str);
        }
        stringList.add(info);

        //写入
        FileOutputStream fos = new FileOutputStream(s);
        //yong  OutputStreamWrite处理流
        OutputStreamWriter osw = new OutputStreamWriter(fos);

        Iterator<String> iterator = stringList.iterator();
        while (iterator.hasNext()){
            osw.write(iterator.next() + "\n");
        }
        osw.close();

    }
}
